/**
 * 配置数据访问服务
 */
const fs = require('fs').promises;
const { CONFIG_FILE } = require('../utils/constants');

/**
 * 读取全局配置
 */
async function readConfig() {
    try {
        const data = await fs.readFile(CONFIG_FILE, 'utf-8');
        return JSON.parse(data);
    } catch (error) {
        // 如果文件不存在，创建默认配置
        console.log('⚠️  配置文件不存在，创建默认配置');
        const defaultConfig = {
            auth: {
                enabled: true,
                defaultUsername: '123',
                defaultPassword: '123',
                sessionTimeout: 24,
                autoLogin: false
            },
            ui: {
                theme: 'dark',
                showUserInfo: true,
                showCameraTips: true,
                showSceneInfo: true,
                panelPosition: 'top-left',
                panelOpacity: 0.7
            },
            camera: {
                defaultPosition: [8, 6, 8],
                defaultTarget: [0, 0, 0],
                minPolarAngle: 0.1,
                maxPolarAngle: 3.07,
                enableDamping: true,
                dampingFactor: 0.05,
                enableZoom: true,
                zoomSpeed: 1.0,
                enablePan: true,
                panSpeed: 1.0,
                enableRotate: true,
                rotateSpeed: 1.0
            },
            editor: {
                enableGeometryLibrary: true,
                enableModelLibrary: true,
                defaultModelPath: 'res/models/',
                previewOpacity: 0.6,
                previewAnimation: true,
                dragLabelEnabled: true
            },
            performance: {
                enableShadows: true,
                shadowMapSize: 2048,
                antialias: true,
                maxFPS: 60,
                enableStats: false
            },
            debug: {
                enabled: false,
                showConsole: true,
                logLevel: 'info',
                showFPS: false,
                showMemory: false
            }
        };
        await saveConfig(defaultConfig);
        return defaultConfig;
    }
}

/**
 * 保存全局配置
 */
async function saveConfig(config) {
    await fs.writeFile(CONFIG_FILE, JSON.stringify(config, null, 2), 'utf-8');
    console.log('✅ 全局配置已保存到:', CONFIG_FILE);
}

module.exports = {
    readConfig,
    saveConfig
};

